package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;

import java.awt.Color;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.ImageIcon;

import BUS.Client;
import BUS.CommandFromClient;
import BUS.DataPackageFromServer;
import BUS.CommandFromClient.COMMAND_ID;
import BUS.DataPackageFromServer.DATA_ID;
import DTO.ColInfoDTO;
import DTO.RecordDTO;
import DTO.TableDTO;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MainScreen extends JFrame {

	private JPanel contentPane;
	/**
	 * @wbp.nonvisual location=-28,279
	 */
	private final JTextArea textArea = new JTextArea();
	private JTextArea textArea_Query;
	private static String IP = "127.0.0.1";
	private static int port = 3200;
	private static Client client;
	private JTable tableOutput;
	private JMenuItem mntmConnectToServer;
	private JScrollPane scrollPane;
	private JLabel labelOutputText;

	public void SetIP(String ip) {
		IP = ip;
	}

	public void SetPort(int port) {
		this.port = port;
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainScreen frame = new MainScreen();
					frame.setVisible(true);
					client = new Client();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public void connect() {
		client.ConnectTo(IP, port);
		if (client.isConneccted())
			JOptionPane.showMessageDialog(contentPane, "Connect successful !");
		else
			JOptionPane.showMessageDialog(contentPane, "Connect fail !");
	}

	/**
	 * Create the frame.
	 */
	public MainScreen() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				client.SendCommand(new CommandFromClient(COMMAND_ID.EXIT, ""));
			}
		});
		setIconImage(Toolkit
				.getDefaultToolkit()
				.getImage(
						MainScreen.class
								.getResource("/Resource/User-Clients-icon.png")));
		setTitle("ClientModule");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		try {
			for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (UnsupportedLookAndFeelException e) {
			// handle exception
		} catch (ClassNotFoundException e) {
			// handle exception
		} catch (InstantiationException e) {
			// handle exception
		} catch (IllegalAccessException e) {
			// handle exception
		}
		setBounds(100, 100, 756, 474);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnConnect = new JMenu("Connect");
		menuBar.add(mnConnect);

		mntmConnectToServer = new JMenuItem("Connect to server");
		mntmConnectToServer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mntmConnectToServer_actionPerformed();
			}
		});
		mnConnect.add(mntmConnectToServer);

		JMenuItem mntmDisconnect = new JMenuItem("Disconnect");
		mntmDisconnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mntmDisconnect_actionPerformed();
			}
		});
		mnConnect.add(mntmDisconnect);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JPanel Panel_Bottom = new JPanel();
		Panel_Bottom.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
		Panel_Bottom.setBackground(Color.WHITE);

		JPanel Panel_Top = new JPanel();
		Panel_Top.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
		Panel_Top.setBackground(Color.WHITE);

		JLabel lblNewLabel = new JLabel("OUTPUT");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane
				.setHorizontalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_contentPane
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																Alignment.TRAILING,
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				Panel_Top,
																				GroupLayout.DEFAULT_SIZE,
																				710,
																				Short.MAX_VALUE)
																		.addContainerGap())
														.addGroup(
																Alignment.TRAILING,
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				lblNewLabel)
																		.addGap(330))
														.addGroup(
																Alignment.TRAILING,
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				Panel_Bottom,
																				GroupLayout.DEFAULT_SIZE,
																				710,
																				Short.MAX_VALUE)
																		.addContainerGap()))));
		gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_contentPane
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(Panel_Top, GroupLayout.PREFERRED_SIZE,
								84, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lblNewLabel)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(Panel_Bottom, GroupLayout.DEFAULT_SIZE,
								311, Short.MAX_VALUE).addContainerGap()));

		labelOutputText = new JLabel("Message:");

		scrollPane = new JScrollPane();
		scrollPane.setVisible(false);
		GroupLayout gl_Panel_Bottom = new GroupLayout(Panel_Bottom);
		gl_Panel_Bottom
				.setHorizontalGroup(gl_Panel_Bottom
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_Panel_Bottom
										.createSequentialGroup()
										.addGap(20)
										.addGroup(
												gl_Panel_Bottom
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(
																scrollPane,
																GroupLayout.PREFERRED_SIZE,
																669,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(
																labelOutputText))
										.addContainerGap(19, Short.MAX_VALUE)));
		gl_Panel_Bottom.setVerticalGroup(gl_Panel_Bottom.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_Panel_Bottom
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(labelOutputText)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE,
								211, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(19, Short.MAX_VALUE)));

		tableOutput = new JTable();
		tableOutput.setModel(new DefaultTableModel(new Object[][] {
				{ "a", "b" }, { null, null }, }, new String[] { "New column",
				"New column" }));
		scrollPane.setViewportView(tableOutput);
		Panel_Bottom.setLayout(gl_Panel_Bottom);

		JButton btnExecute = new JButton("");
		btnExecute.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				ExecuteQueryProcessing();
			}
		});
		btnExecute.setIcon(new ImageIcon(MainScreen.class
				.getResource("/Resource/icon_run.png")));

		textArea_Query = new JTextArea();
		GroupLayout gl_Panel_Top = new GroupLayout(Panel_Top);
		gl_Panel_Top.setHorizontalGroup(gl_Panel_Top.createParallelGroup(
				Alignment.LEADING).addGroup(
				Alignment.TRAILING,
				gl_Panel_Top
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(textArea_Query, GroupLayout.DEFAULT_SIZE,
								602, Short.MAX_VALUE)
						.addGap(18)
						.addComponent(btnExecute, GroupLayout.PREFERRED_SIZE,
								62, GroupLayout.PREFERRED_SIZE).addGap(16)));
		gl_Panel_Top
				.setVerticalGroup(gl_Panel_Top
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								Alignment.TRAILING,
								gl_Panel_Top
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_Panel_Top
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																textArea_Query,
																Alignment.LEADING,
																GroupLayout.DEFAULT_SIZE,
																60,
																Short.MAX_VALUE)
														.addComponent(
																btnExecute,
																Alignment.LEADING,
																GroupLayout.DEFAULT_SIZE,
																60,
																Short.MAX_VALUE))
										.addContainerGap()));
		Panel_Top.setLayout(gl_Panel_Top);
		contentPane.setLayout(gl_contentPane);
	}

	protected void ExecuteQueryProcessing() {
		// TODO Auto-generated method stub
		if (client.isConneccted()) {
			String sqlStr = textArea_Query.getText();
			sqlStr = sqlStr.trim();
			String[] strings = sqlStr.split(" ");
			if (strings.length == 3) {
				if (strings[0].equals("create")
						&& strings[1].equals("database")) {
					client.SendCommand(new CommandFromClient(COMMAND_ID.CREATE,
							sqlStr));
				}
			}
			client.SendCommand(new CommandFromClient(COMMAND_ID.SQL_STRING,
					sqlStr));
			DataPackageFromServer data = client.RecieveCommand();
			switch (data.get_id()) {
			case MESSAGE: {
				this.labelOutputText.setText("Message: " + data.get_message());
				ShowTableOutput(false);
				break;
			}
			case RESULT: {
				this.labelOutputText.setText("Message: " + data.get_message());
				UpdateOutputTable(data.get_tableResult());
				ShowTableOutput(true);
				break;
			}
			}
		} else {
			// xuat thong bao chua ket noi
			JOptionPane.showMessageDialog(contentPane,
					"Connection isn't established");
		}
	}

	public void mntmConnectToServer_actionPerformed() {
		ConfigConnectionDialog configConnectionDialog = new ConfigConnectionDialog(
				this);
		int x = (this.getWidth() - configConnectionDialog.getWidth()) / 2
				+ this.getX();
		int y = (this.getHeight() - configConnectionDialog.getHeight()) / 2
				+ this.getY();
		configConnectionDialog.setLocation(x, y);
//		configConnectionDialog.show();
		
		configConnectionDialog.setVisible(true);

	}

	public void mntmDisconnect_actionPerformed() {
		client.disconnect();
	}

	public void UpdateOutputTable(TableDTO tableDTO) {
		Vector<RecordDTO> recordList = tableDTO.get_recordList();
		Vector<ColInfoDTO> colList = tableDTO.get_colInfoList();
		int nCol = colList.size();
		int nRecord = recordList.size();

		String[] Cols = new String[nCol];
		String[][] Records = new String[nRecord][nCol];

		for (int i = 0; i < nCol; i++) {
			Cols[i] = colList.get(i).get_colName();
		}

		for (int i = 0; i < nRecord; i++) {
			for (int j = 0; j < nCol; j++) {
				Records[i][j] = recordList.get(i).get_data(j);
			}
		}

		this.tableOutput.setModel(new DefaultTableModel(Records, Cols));

	}

	public void ShowTableOutput(boolean isShowed) {
		this.scrollPane.setVisible(isShowed);
		this.validate();
	}
}
